mui.plusReady(function(){
	loadDatas();
});

function loadDatas(){
	var self = plus.webview.currentWebview();
	var activeItem = localStorage.getItem(KeyCfg.invest_activeTabItem);
	var tabId = plus.storage.getItem('moneychange');
	if(tabId && tabId == 1){
		var gallery = mui('.mui-slider');
		gallery.slider().gotoItem(1); 
	}
	
	localStorage.removeItem(KeyCfg.invest_activeTabItem);
}

mui.init({swipeBack: true});
/**
 * 当点击首页是调用“刷新”事件 
 */
window.addEventListener('reload',function(event){
	window.location.reload();
});

mui.plusReady(function() {
	plus.storage.removeItem(KeyCfg.invest_slideNumber);/*页面加载时，清除当前Tab 选项卡索引号，以便默认显示的是月利宝选项卡*/
	resetDatas();
	loadProjectDatas();
});

function resetDatas(){
	plus.storage.removeItem(KeyCfg.invest_loanSigins_pageNo);/*删除月利宝下拉刷新分页号,以便分页号默认从第1页开始*/
	plus.storage.removeItem(KeyCfg.invest_transfer_pageNo);/*删除债权转让下拉刷新分页号,以便分页号默认从第1页开始*/
	plus.storage.removeItem(KeyCfg.invest_loanSigins_dataState);/*删除月利宝数据加载状态*/
	plus.storage.removeItem(KeyCfg.invest_transfer_dataState);/*删除债权转让数据加载状态*/
}

/*------ Tab选项卡代码 CODE START -----*/
var IdMgr = {
	/**
	 * 新标购买按钮前缀
	 */
	btnLoanIdPrefix :'btnLoan_',
	/**
	 * 债权转让按钮前缀 
	 */
	btnTransferIdPrefix :'btnTransfer_',
};


function plusReady(fn){
   if(window.plus){
	    fn();
	}else{
	    document.addEventListener('plusready',fn,false);
	}
}

function loadProjectDatas(){
	var tabPanel = document.getElementById('cmw-tabPanel');
	plusReady(function(){
		var currNumber = plus.storage.getItem(KeyCfg.invest_slideNumber);
		if(!currNumber) currNumber = 0;
		loadTabContent(0);
		loadTabContent(1);
	});
	tabPanel.addEventListener('slide', function(e) {
		var slideNumber = e.detail.slideNumber;
		plus.storage.setItem(KeyCfg.invest_slideNumber,slideNumber+"");
		$("#TypeSelect div").each(function(){
			if($(this).attr('id')=='TypeSelected'){
				$(this).removeAttr('id');
				$(this).removeClass('activity');
			}else{
				$(this).attr('id','TypeSelected');
				$(this).addClass('activity');
			}
		});
	});
}

/**
	 * 根据所选Tab加载相应的最新项目或债权转让数据 
	 * @param {Object} slideNumber
	 * @param callback 回调函数
	 */
	function loadTabContent(slideNumber,callback){
		var isLoanSigins = true;
		var itemId = "app_siginLoans";
		var url = UrlConfig.invest_allLoanSigns;
		var sessionId = plus.storage.getItem(KeyCfg.JSESSIONID);
		var pageNo = plus.storage.getItem(KeyCfg.invest_loanSigins_pageNo);
		if(slideNumber == 1){
			itemId = "app_transferLoans";
			url = UrlConfig.invest_transfersloan_list; 
			isLoanSigins = false;
			pageNo = plus.storage.getItem(KeyCfg.invest_transfer_pageNo);
		}

		if(!pageNo) pageNo = 1;
		var isAppend = (pageNo && parseInt(pageNo) > 1) ? true : false;
		var pars = { sessionId : sessionId,pageno : pageNo,pagesize : 5};
	     $.ajax(url, {  
	        data:pars,  
	        dataType: 'jsonp',  
	        crossDomain: true,  
	        success: function(data) {
	        		data = JSON.parse(data);
	        		var totalSize = data.totalSize;
	        		var dataState = data.dataState || 1;
	        		dataState += "";
	        		var list = data.list;
	        		var eleIds = null;
	        		
	        		if(isLoanSigins){
	        			plus.storage.setItem(KeyCfg.invest_loanSigins_dataState,dataState);
	        			eleIds = loadLoanSigins(itemId,list,isAppend);
	        		}else{
	        			plus.storage.setItem(KeyCfg.invest_transfer_dataState,dataState);
	        			eleIds = loadTranLoans(itemId,list,isAppend);
	        		}
				addClickListeners(eleIds);

				$('.myStat4').circliful();
				if(callback) callback();
	        }
	     });
	}
	
	
	/**
	 * 加载最新项目（借款标）
	 * @param {Object} data
	 */
	function loadLoanSigins(itemId,data,isAppend){
		if(!data || data.length == 0) return null;
		var eleIds = [];
		var htmlArr = [];
		var count = data.length;
		for(var i=0; i<count; i++){
			var rowData = data[i];
			var id = rowData.id;
			var loanTitle = rowData.loanTitle;
			var thisIssueLoan = rowData.thisIssueLoan;
			var rateYear = rowData.rateYear;
			var rateYearDiscount = rowData.rateYearDiscount;
			var refundDeadline = rowData.refundDeadline;
			var residue = rowData.residue;
			var percent = rowData.percent;
			var loanState = rowData.loanState;
			var btnId = IdMgr.btnLoanIdPrefix +id;
			eleIds[eleIds.length] = btnId;
			var btnHtml;
			var circleHtml;
			if(loanState == '满标'){
				btnHtml = '<button style="z-index:99;color: #3A8Ec6;background: none;border: none;font-size: 13px;margin-right:15px" type="button" class="mui-btn mui-btn-danger" >满标</button>';
			    circleHtml ='<div style="color: #3A8Ec6;float:right" class="myStat4" data-dimension="120" data-text="100%" data-info="New Clients" data-width="12" data-fontsize="16" data-percent="100" data-fgcolor="#0b56a7" data-bgcolor="#7AC1ED"></div>';
			}
			if(loanState == '回款中'){
				btnHtml = '<button style="z-index:99;color: #7E7E7E;background: none;border: none;font-size: 13px;margin-right:8px" type="button" class="mui-btn mui-btn-danger" >还款中</button>';
				circleHtml ='<div style="color: #7E7E7E;float:right" class="myStat4" data-dimension="120" data-text="100%" data-info="New Clients" data-width="12" data-fontsize="16" data-percent="100" data-fgcolor="#7E7E7E" data-bgcolor="#7E7E7E"></div>';
			}
			if(percent < 100){
				btnHtml = '<button style="z-index:99;color: #f98a38;background: none;border: none;font-size: 13px;margin-right:15px;" class="mui-btn mui-btn-danger" >投标</button>';
				circleHtml = '<div style="color: #3A8Ec6;float:right" class="myStat4" data-dimension="120" data-text="'+percent+'%" data-info="New Clients" data-width="12" data-fontsize="16" data-percent="'+percent+'" data-fgcolor="#0b56a7" data-bgcolor="#7AC1ED"></div>';
			}
			var arr = 	[
            '<li >',
			'	<div class="app_projects_item_content">',
			'		<div class="app_projects_item_content_left">',
			'			<div class="app_projects_item_content_info">',
			'				<a id="'+id+'" href="javascript:void(0)" >'+loanTitle+'</a>',
			'				<span>&nbsp;&nbsp;</span>',
			'				<span class="app_assurance_hight">100%本息保障</span>',
			'			</div>',
			'			<div class="app_projects_item_rate_info">',
			'				<div class = "app_projects_item_rate_info_left"> ',
			'					<span class="fontBigRate mui-blue">'+rateYear+'%</span>',
			'		            <span class="fontSmallRate mui-orange">+'+rateYearDiscount+'%</span>',
			'				</div>',
			'			<div class = "app_projects_item_rate_info_right">',
            '                <span class="fontMiddleRate">'+refundDeadline+'个月</span>',
			'			</div>',
			'		</div>',
			'		<div class="app_projects_item_rate_info pdt20">',
			'			<div class = "app_projects_item_rate_info_left"> ',
			'				<span class="fontMoney">借款金额:</span>',
			'		        <span class="fontMoney">'+thisIssueLoan+'</span>',
			'			</div>',
			'			<div class = "app_projects_item_rate_info_right">',
            '                <span class="fontMoney">剩余:</span>',
			'		        <span class="fontMoney">￥'+residue+'</span>',
			'			</div>',
			'		</div>',
			'	</div>',
			'	<div class="app_projects_item_invest" id="'+btnId+'">',
			'		<div class="app_projects_item_invest_inner">',
			            btnHtml,
			'		</div>',
			'		<div id="main">',
			'			<div class="demo">',
			            circleHtml,
			'				<div style="clear:both"></div>',
			'			</div>',
			'		</div>',
			'	</div>',
			'   </div>',
            ' </li>'			
			];
			htmlArr[htmlArr.length] = arr.join(" ");
		}
		var htm = htmlArr.join(" ");
		var itemEle = $("#"+itemId);
		if(!isAppend){
			itemEle.html(htm);
		}else{
			itemEle.append(htm);
		}
		return eleIds;
	}


	/**
	 * 加载债权转让
	 * @param {Object} data
	 */
	function loadTranLoans(itemId,data,isAppend){
		if(!data || data.length == 0) return null;
		var eleIds = [];
		var htmlArr = [];
		var count = data.length;
		for(var i=0; i<count; i++){
			var rowData = data[i];
			var id = rowData.id;
			var Tid = '\''+rowData.id+'\'';
			var loanTitle = rowData.loanTitle;
			var tenderMoney = rowData.tenderMoney;
			var rateYear = rowData.rateYear;
			var refundDeadline = rowData.refundDeadline;
			var period = rowData.period;
			var sellMoney = rowData.sellMoney;
			var effectiveYield = rowData.effectiveYield;
			var btnId = IdMgr.btnTransferIdPrefix+id;
			var status = rowData.status;
			var transfersTime = rowData.transfersTime;
			if(!status) status = "暂停";
			if(status == "购买"){
				eleIds[eleIds.length] = btnId;
				btnHtml = '<button style="z-index:99;color: #f98a38;background: none;border: none;font-size: 17px;margin-right: 11px;" type="button" class="mui-btn mui-btn-danger" >购买</button>'
			    circleHtml = '<div style="float:right" class="myStat4" data-dimension="120" data-text="" data-info="New Clients" data-width="12" data-fontsize="16" data-percent="100" data-fgcolor="#f98a38" data-bgcolor="#f98a38"></div>';
			}else if(status == "暂停"){
                btnHtml = '<button style="z-index:99;color: #7e7e7e;background: none;border: none;font-size: 17px;margin-right: 11px;" type="button" class="mui-btn mui-btn-danger" >暂停</button>'
			    circleHtml = '<div style="float:right" class="myStat4" data-dimension="120" data-text="" data-info="New Clients" data-width="12" data-fontsize="16" data-percent="100" data-fgcolor="#7e7e7e" data-bgcolor="#7e7e7e"></div>';				
			}else {
				eleIds[eleIds.length] = btnId;
                btnHtml = '<button style="z-index:99;color: #7e7e7e;background: none;border: none;font-size: 17px;margin-right: 3px;" type="button" class="mui-btn mui-btn-danger" >'+status+'</button>'
			    circleHtml = '<div style="float:right" class="myStat4" data-dimension="120" data-text="" data-info="New Clients" data-width="12" data-fontsize="16" data-percent="100" data-fgcolor="#7e7e7e" data-bgcolor="#7e7e7e"></div>';
			}
			
			var arr =[
            '<li >',
			'	<div class="app_projects_item_content">',
			'		<div class="app_projects_item_content_left">',
			'			<div class="app_projects_item_content_info">',
			'				<a id="'+id+'" href="javascript:void(0)" >'+loanTitle+'</a>',
			'				<span>&nbsp;&nbsp;</span>',
			'				<span class="app_assurance_hight">100%本息保障</span>',
			'			</div>',
			'			<div class="app_projects_item_rate_info">',
			'				<div class = "app_projects_tranfer_info_left"> ',
			'					<span class="fontBigRate mui-blue">'+effectiveYield+'%</span>',
			'				</div>',
			'			<div class = "app_projects_tranfer_info_right">',
            '                <span class="fontMiddleRate1">剩余期限:'+period+'个月</span>',
			'			</div>',
			'		</div>',
			'		<div class="app_projects_item_rate_info pdt20">',
			'			<div class = "app_projects_tranfer_info_left"> ',
			'				<span class="fontMoney">'+transfersTime+'</span>',
			'			</div>',
			'			<div class = "app_projects_tranfer_info_right">',
            '                <span class="fontMoney">债权价格:</span>',
			'		        <span class="fontMoney">￥'+tenderMoney+'</span>',
			'			</div>',
			'		</div>',
			'	</div>',
			'	<div class="app_projects_item_invest" id="'+btnId+'">',
			'		<div class="app_projects_item_tranfer_inner">',
			            btnHtml,
			'		</div>',
			'		<div id="main">',
			'			<div class="demo">',
			            circleHtml,
			'				<div style="clear:both"></div>',
			'			</div>',
			'		</div>',
			'	</div>',
			'   </div>',
            ' </li>'
			];
			htmlArr[htmlArr.length] = arr.join(" ");
		}
	
		var htm = htmlArr.join(" ");
		var itemEle = $("#"+itemId);
		var scrollTop = itemEle.scrollTop();
		if(!isAppend){
			itemEle.html(htm);
			//$("#item1mobile").scrollTop(100);
		}else{
			itemEle.append(htm);
		}
		return eleIds;
	}
	
	//月利宝标标题的点击事件
	function openLoan(id){
		var pars = {formId:id};
		var cfg = {pars : pars};
		MuiEventMgr.openBySafe('../buy/buy.html',cfg);	
	}

	//债权转让标标题的点击事件
	function openTransfer(Tid){
		var pars = {formId:Tid};
		var cfg = {pars : pars};
		MuiEventMgr.openBySafe('../transfer/transfer.html',cfg);	
	}

	/**
	 * 为新标，债权转让购买按钮添加单击事件
	 */
	function addClickListeners(eleIds){
		if(!eleIds || eleIds.length == 0) return;
		var buttons = mui(".mui-btn");
		for(var i=0,count=eleIds.length; i<count; i++){
			var eleId = eleIds[i];
			var ele = CmwMcore.$(eleId);
			MeventMgr.onTouchstart(ele,function(event,self){
				var eleId = self.id;
				var url = "../buy/buy.html";
				var pars = {};
				if(eleId.indexOf(IdMgr.btnLoanIdPrefix) != -1){/*投标页面*/
					url = "../buy/buy.html";
					var id = eleId.replace(IdMgr.btnLoanIdPrefix,"");
					pars = {formId:id};
				}else{/*债权转让页面*/
					url = "../transfer/transfer.html";
					var id = eleId.replace(IdMgr.btnTransferIdPrefix,"");
					pars = {formId:id};
				}
				var cfg = {pars : pars};
				MuiEventMgr.openBySafe(url,cfg);
			});
		}
	}
/*------ Tab选项卡代码 CODE END -----*/

/*------选项卡下拉刷新代码 CODE END -----*/
(function($) {
	//阻尼系数
	var deceleration = mui.os.ios?0.003:0.0009;
	$('.mui-scroll-wrapper').scroll({
		bounce: false,
		indicators: true, //是否显示滚动条
		deceleration:deceleration
	});
	$.ready(function() {
		//循环初始化所有下拉刷新，上拉加载。
		$.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function(index, pullRefreshEl) {
			$(pullRefreshEl).pullToRefresh({
//				down: {
//					callback: function() {
//						alert("index"+index+",down");
//						var self = this;
//						setTimeout(function() {
//							alert("index"+index+",down");
////							var ul = self.element.querySelector('.mui-table-view');
////							ul.insertBefore(createFragment(ul, index, 10, true), ul.firstChild);
//							self.endPullDownToRefresh();
//						}, 1000);
//					}
//				},
				up: {
				    contentover : "释放立即刷新",//可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
				    contentrefresh : "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
					callback: function() {
						var self = this;
						if(checkFinish(index)){/*如果数据已读取完成，就停止加载更多*/
							self.endPullUpToRefresh();
							return;
						}
						setTimeout(function() {
							setPageNo(index);
							loadDatas(function(){
								self.endPullUpToRefresh();
							});
						}, 1000);
					}
				}
			});
		});
		
		/**
		 * 检查下拉刷新数据是否已全部读取完成 
		 * @param {Object} index
		 */
		function checkFinish(index){
			var key = null;
			if(index == 1){/*债权转让下拉刷新加载后的数据状态*/
				key = KeyCfg.invest_transfer_dataState;
			}else{/*月利宝下拉刷新加载后的数据状态*/
				key = KeyCfg.invest_loanSigins_dataState;
			}
			var dataState = plus.storage.getItem(key);
			return (null == dataState || parseInt(dataState) == 1) ? false : true;
		}
		
		/**
		 * 设置分页数 
		 * @param {Object} index
		 */
		function setPageNo(index){
			var key = null;
			if(index == 1){/*债权转让下拉刷新加载*/
				key = KeyCfg.invest_transfer_pageNo;
			}else{/*月利宝下拉刷新加载*/
				key = KeyCfg.invest_loanSigins_pageNo;
			}
			var pageNo = plus.storage.getItem(key);
			if(!pageNo) pageNo = "1";
			pageNo = parseInt(pageNo);
			pageNo++;
			plus.storage.setItem(key,pageNo+"");
		}
		
	   function loadDatas(callback){
	   		var currNumber = plus.storage.getItem(KeyCfg.invest_slideNumber);
			if(!currNumber) currNumber = 0;
			loadTabContent(currNumber,callback);
	   }
	});
})(mui);
